<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>插件</title>
      <style>
          * {
              margin: 0;
              padding: 0;
              box-sizing: border-box;
          }

          div {
              position: relative;
              width: 500px;
              height: 500px;
              background: #ece9e9;
              margin: 100px auto;
          }

          ul {
              display: flex;
              flex-wrap: wrap;
              margin: 10px;
          }

          li {
              display: block;
              width: 40px;
              list-style: none;
              margin: 3px;
          }

          li input {
              width: 100%;
          }

          span {
              display: block;
              width: 100px;
              height: 30px;
              position: absolute;
              bottom: 0;
          }

          .zhi {
              width: 100%;
          }
      </style>
   </head>
   <body>
      <div>
         <ul id="list">
         </ul>
         <button id="addButton">添加</button>
         <span>总值：<input class="zhi" type="text" readonly></span>
      </div>
      <script>
         const arr = [];

         function render(arr) {
            const ul = document.getElementById('list');
            ul.innerHTML = arr.map((ele, index) => {
               return `<li><input type="text" value="${ele}" data-index="${index}"></li>`;
            }).join('');

            // 为每个输入框添加 input 事件监听器
            document.querySelectorAll('#list li input').forEach(input => {
               input.addEventListener('input', updateTotal);
            });
         }

         function updateTotal() {
            const inputs = document.querySelectorAll('#list li input');
            let total = 0;

            inputs.forEach(input => {
               const value = parseFloat(input.value);
               if (!isNaN(value)) {
                  total += value;
               }
            });

            document.querySelector('.zhi').value = total;
         }

         document.getElementById('addButton').addEventListener('click', function () {
            // 获取当前所有输入框的值
            const currentValues = Array.from(document.querySelectorAll('#list li input')).map(input => input.value);

            // 将当前值保存到数组中
            arr.length = 0; // 清空数组
            arr.push(...currentValues);

            // 添加一个新的空输入框
            arr.push('');

            render(arr);
            updateTotal(); // 更新总值
         });

         render(arr);
         updateTotal(); // 初始渲染后更新总值
      </script>
   </body>
</html>
